from uuid import UUID, uuid4

from PyQt5.QtWidgets import QVBoxLayout, QWidget, QPushButton, QTreeView, QAbstractItemView
from PyQt5.QtCore import Qt, QModelIndex
from PyQt5.QtGui import QStandardItemModel

from protolib.gui_utils.pyqt5_messageboxes import show_question_messagebox

from data import database

from player.dialogs.editors.genre import GenreEditor

class GenreList(QWidget):
    GENRE_NAME, GENRE_UUID = range(2)

    def __init__(self):
        super().__init__(None)

        layout = QVBoxLayout()

        self.genre_list = QTreeView()
        self.genre_list.doubleClicked.connect(self.genre_list_double_clicked)
        self.genre_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.genre_list_model = QStandardItemModel(0, 2, self)
        self.genre_list.setModel(self.genre_list_model)
        self.genre_list_model.setHeaderData(self.GENRE_NAME, Qt.Horizontal, "Name")
        self.genre_list_model.setHeaderData(self.GENRE_UUID, Qt.Horizontal, "UUID")
        layout.addWidget(self.genre_list)
        self.refresh_genre_list()

        self.create_genre_button = QPushButton('Create Genre')
        self.create_genre_button.clicked.connect(self.create_genre)
        layout.addWidget(self.create_genre_button)

        self.delete_genre_button = QPushButton('Delete Genre')
        self.delete_genre_button.clicked.connect(self.delete_genre)
        layout.addWidget(self.delete_genre_button)

        self.setLayout(layout)

    def refresh_genre_list(self):
        self.genre_list_model.removeRows(0, self.genre_list_model.rowCount())
        for uuid in sorted(database['genres'], key=lambda x: str(database['genres'][x]['name']) if database['genres'][x]['name'] else 'No Name', reverse=True):
            self.genre_list_model.insertRow(0)
            self.genre_list_model.setData(self.genre_list_model.index(0, self.GENRE_NAME), database['genres'][uuid]['name'] if database['genres'][uuid]['name'] else 'No Name')
            self.genre_list_model.setData(self.genre_list_model.index(0, self.GENRE_UUID), str(uuid))

        self.genre_list.resizeColumnToContents(self.GENRE_NAME)
        self.genre_list.resizeColumnToContents(self.GENRE_UUID)

    def uuid_from_index(self, index: QModelIndex) -> UUID:
        index = self.genre_list_model.index(index.row(), self.GENRE_UUID)
        item = self.genre_list_model.itemFromIndex(index)
        uuid = item.text()
        return UUID(uuid)

    def genre_list_double_clicked(self, index: QModelIndex):
        uuid = self.uuid_from_index(index)
        editor = GenreEditor(uuid)
        editor.exec_()
        self.refresh_genre_list()

    def create_genre(self):
        uuid = uuid4()
        genre = {
            'name': 'New Genre',
            'artist': None,
            'cover': None
        }
        database['genres'][uuid] = genre
        editor = GenreEditor(uuid)
        editor.exec_()
        self.refresh_genre_list()

    def delete_genre(self):
        if not show_question_messagebox('Are you sure?', 'You are about to permanently delete a genre. All tracks associated with this genre will have there genre associations reset. This action cannot be undone.'):
            return
        if not self.genre_list.selectedIndexes():
            return
        index = self.genre_list.selectedIndexes()[0]
        uuid = self.uuid_from_index(index)
        for track_uuid in database['music']:
            if database['music'][track_uuid]['genre'] == uuid:
                database['music'][track_uuid]['genre'] = None
        del database['genres'][uuid]
        self.refresh_genre_list()
